package com.wffz.task;

import com.wffz.dto.AwardDTO;
import com.wffz.po.Patch;
import com.wffz.service.PatchService;
import com.wffz.websocket.ParitySocket;
import com.wffz.websocket.SapreSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.EncodeException;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author sunlei
 * @className SocketTestTask
 * @Description
 * @date 2023-02-18 9:40
 **/
@Component
@EnableScheduling
@Slf4j
public class SocketSapreTask {

    @Resource
    private PatchService patchService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    static String patchType = "1";

    @Scheduled(cron = "0/1 * * * * ?")
    public void test() {
//        log.error("********* 定时任务执行 sapre  Task  **************");
        String v = stringRedisTemplate.opsForValue().get("task_business");
        if ("0".equals(v)) {
//            log.error("业务定时任务未开启");
            return;
        }
        // 获取当天当前期
        Patch patch = patchService.getCurrentPeriod(patchType);
        if (patch == null) {
            log.error(" patch is null ............");
            return;
        }

        CopyOnWriteArraySet<SapreSocket> webSocketSet = SapreSocket.getWebSocketSet();
        int i = 0;
        webSocketSet.forEach(c -> {
            try {
//                c.sendMessage(" 定时发送 " + new Date().toLocaleString());
                c.sendObjMessage(patch);
            } catch (IOException | EncodeException e) {
                e.printStackTrace();
            }
        });

        // 获取当前期码
        String patchNum = patch.getPatchNum();
        // 倒数
        int countDown = patch.getCountDown();
        // 获取下期期码
        String nextPatchNum = String.valueOf(Long.parseLong(patchNum) + 1);
        // 下期期码对象
        Patch nextPatch = patchService.getPatchByNum(nextPatchNum, patchType);
        // 当倒计时为5,获取数据，开奖颜色
        if (countDown == 15) {
            AwardDTO awardDTO = patchService.awardColor(patchNum,patchType);
            patch.setPrizesColor(awardDTO.getColor());
            patch.setPrizesNum(awardDTO.getNumber());
            patchService.updatePatch(patch);
        }

        // 当倒计时为0,设置下期为当前期
        if (countDown == 0) {
            patch.setStatus("2");
            nextPatch.setStatus("1");
            patchService.updatePatch(nextPatch);
        }
        countDown--;
//        log.info("countDown : " + countDown);
        patch.setCountDown(countDown);
        patchService.updatePatch(patch);
//        log.error("/n 定时任务完成.......");
    }


}